import React from 'react';
import { ImagePicker, WingBlank, Toast } from 'antd-mobile';
import 'antd-mobile/dist/antd-mobile.css';

class Sharefabu extends React.Component {
	constructor(props) {
	  super(props);
	  this.state = {
        files: [],
        files_ok: [],
        title:'',
        content:'',
        time:'',
        name:localStorage.getItem('username'),
        id:localStorage.getItem('userid'),
	  };
	}
    
    /*显示选择的图片*/
    onChange = (files, type, index) => {
        this.setState({
            files,
        });
    }

    /*上传动态*/
    async uploadsay(){
    
        //1、如果图片数组为空
        if(this.state.files == []){
           const sayparam={
                username: this.state.name,
                userid:  this.state.id,
                commentnum: 0,
                likenum: 0,
                title: this.state.title,
                content: this.state.content,
            }
            //添加动态
            await fetch('https://www.prebeauty.work/saying', {
                method: 'POST',
                body: JSON.stringify(sayparam),
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then((res) => res.json() )
            .then((res) => {
                console.log(res);
                this.props.history.push('/Share');
                Toast.success('成功发布',1);
            })
            
        //2、如果图片数组不为空
        }else{
            //(1)一张张上传图片到服务器
            console.log(this.state.files)
            for(var i=0; i<this.state.files.length; i++){
                // 实例化一个表单数据对象
                var formData = new FormData();
                console.log(this.state.files[i].file)
                formData.append('fileName', this.state.files[i].file.name);
                formData.append('file', this.state.files[i].file);
                await fetch(`https://www.prebeauty.work/upload`, {
                        method: 'POST',
                        body: formData,  
                })
                .then((res) => res.json())
                .then((res) => {
                    console.log(res);
                    if (res.status == 'done') {
                        this.setState({
                            files_ok: [...this.state.files_ok,res.name]
                        })
                    }
                    else {
                        alert('添加失败')
                    }    
                })     
            }
            //把上传到服务器成功后的图片数组转化为字符串
            var files_ok_string = ''
            for(var i=0; i<this.state.files_ok.length; i++){
                if( i == 0){
                    files_ok_string = this.state.files_ok[i]
                }else{
                    files_ok_string = files_ok_string + ';' + this.state.files_ok[i]
                }
            } 
           //(2)发送数据
           const sayparam={
                username: this.state.name,
                userid:  this.state.id,
                imagefile: files_ok_string,
                commentnum: 0,
                likenum: 0,
                title: this.state.title,
                content: this.state.content,
            }
            //发送请求，动态所有内容存到服务器
            await fetch('https://www.prebeauty.work/saying', {
                method: 'POST',
                body: JSON.stringify(sayparam),
                headers: {
                    'Content-Type': 'application/json'
                },
            })
            .then((res) => res.json() )
            .then((res) => {
                console.log(res);
                this.props.history.push('/Share');
                Toast.success('成功发布',1);
            })
        }
    }

	render() {
        const { files } = this.state;

        return (
            <div className='share-fabu'> 
                {/*导航栏 */}
                <div className='share-nav'>
                    <p
                        style={{
                            width: '10%',
                            height: 30,
                            marginTop: 20,
                            marginLeft: '5%',
                            float: 'left'
                        }}
                        onClick={()=>{
                            this.props.history.push('/Share');
                            Toast.fail('取消发布',1);
                        }}
                    >取消</p>
                    <div 
                        style={{
                            position:'absolute',
                            top:'20px',
                            left:'40%'
                        }}
                    >发动态</div>
                    <button 
                        style={{
                            width:'20%',
                            height:'40px',
                            borderRadius:'20px',
                            backgroundColor: '#95D2AA',
                            position:'absolute',
                            right:'5%',
                            top:'5px'
                        }}
                        onClick={this.uploadsay.bind(this)}
                    >发布
                    </button>
                </div>

                {/*动态文本 */}
                <textarea 
                    placeholder='写下你的标题：）'
                    style={{
                        width:'92%',
                        height:'30px',
                        border:'none',
                        resize: 'none',
                        outline: 'none',
                        fontSize:'19px',
                        marginTop:'10px',
                        padding: '10px',
                        lineHeight:1.5,
                        backgroundColor:'#f5f5f5'
                    }}
                    onChange={(e)=>{
                        this.setState({
                            title:e.target.value 
                        })
                    }}
                >
                </textarea>
                <textarea 
                    placeholder='交流新鲜事，让更多的人了解你...'
                    style={{
                        width:'92%',
                        height:'300px',
                        border:'none',
                        resize: 'none',
                        outline: 'none',
                        fontSize:'15px',
                        padding: '10px',
                        lineHeight:1.5,
                        marginTop:'10px',
                        backgroundColor:'#f5f5f5'
                    }}
                    onChange={(e)=>{
                        this.setState({
                            content:e.target.value 
                        })
                    }}
                >
                </textarea>

                {/*上传动态图片 */}
                <WingBlank>
                    <ImagePicker
                        files={files}
                        onChange={this.onChange}
                        onImageClick={(index, fs) => console.log(index, fs)}
                        length={3}
                        selectable={files.length < 9} 
                        multiple={true}  
                    />
                </WingBlank>
                
            </div>  
        )
    }
}

export default Sharefabu